using System;
using System.IO;
using System.Net;
using System.Text;
using Android.Util;

namespace CometServiceDemo.Comet
{
    public class CometRequest
    {
        private readonly string _uri;
        //public static ManualResetEvent allDone = new ManualResetEvent(false);
        public CometRequest(string uri)
        {
            _uri = uri;
        }

        private const int BufferSize = 4096;

        public  event OnReceiveDataDelegate OnReceiveData;
        private HttpWebRequest _myHttpWebRequest1;
        private RequestState _myRequestState;
        public void BeginRequest()
        {
            try
            {                
                _myHttpWebRequest1 = null;
                _myRequestState = null;
                // Create a HttpWebrequest object to the desired URL.
                _myHttpWebRequest1 = (HttpWebRequest) WebRequest.Create(_uri);
                _myHttpWebRequest1.Method = "post";
                _myHttpWebRequest1.KeepAlive = true;
                _myHttpWebRequest1.ContentType = "text/html; charset=UTF-8";
                // Create an instance of the RequestState and assign the previous myHttpWebRequest1
                // object to it's request field.  
                _myRequestState = new RequestState();
                _myRequestState.Request = _myHttpWebRequest1;


                // Start the asynchronous request.
                IAsyncResult result =
                    (IAsyncResult) _myHttpWebRequest1.BeginGetResponse(new AsyncCallback(RespCallback), _myRequestState);

                //allDone.WaitOne();

                // Release the HttpWebResponse resource.
                //myRequestState.response.Close();
            }
            catch (WebException e)
            {
                Log.Error(this.GetType().ToString(), "\nException raised!");
                Log.Error("Message:{0}", e.Message);
                Log.Error("Status:{0}", e.Status.ToString());
            }
            catch (Exception e)
            {
                Log.Error(this.GetType().ToString(), "\nException raised!");
                Log.Error("Source :{0} ", e.Source);
                Log.Error("Message :{0} ", e.Message);
            }
        }
        public void StopRequest()
        {
            if(_myHttpWebRequest1!=null)
            {
                _myHttpWebRequest1.Abort();
            }
        }

        private  void RespCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                // State of request is asynchronous.
                RequestState myRequestState = (RequestState) asynchronousResult.AsyncState;
                HttpWebRequest myHttpWebRequest2 = myRequestState.Request;
                myRequestState.Response = (HttpWebResponse) myHttpWebRequest2.EndGetResponse(asynchronousResult);

                // Read the response into a Stream object.
                Stream responseStream = myRequestState.Response.GetResponseStream();
                myRequestState.StreamResponse = responseStream;
                myRequestState.RequestData.Clear();
                // Begin the Reading of the contents of the HTML page and print it to the console.
                IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BufferSize,
                                                                              new AsyncCallback(ReadCallBack),
                                                                              myRequestState);
            }
            catch (Exception e)
            {
                Log.Error(this.GetType().ToString(), "\nException raised!");
                Log.Error("\nMessage:{0}", e.Message);
                Log.Error("\nStatus:{0}", e.Message.ToString());

            }
        }
        private  void ReadCallBack(IAsyncResult asyncResult)
        {
            try
            {

                RequestState myRequestState = (RequestState) asyncResult.AsyncState;
                Stream responseStream = myRequestState.StreamResponse;
                int read = responseStream.EndRead(asyncResult);
                // Read the HTML page and then print it to the console.
                if (read > 0)
                {
                    //myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
                    IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, BufferSize,
                                                                               new AsyncCallback(ReadCallBack),
                                                                               myRequestState);

                    if(OnReceiveData!=null)
                    {
                        OnReceiveData(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
                    }
                }
                //else
                //{
                //    Console.WriteLine("\nThe contents of the Html page are : ");
                //    if (myRequestState.requestData.Length > 1)
                //    {
                //        string stringContent;
                //        stringContent = myRequestState.requestData.ToString();
                //        Console.WriteLine(stringContent);
                //        if(this.OnReceiveData!=null)
                //        {
                //            this.OnReceiveData(stringContent);
                //        }
                //    }
                //    //Console.WriteLine("Press any key to continue..........");
                //    //Console.ReadLine();

                //    responseStream.Close();
                //    allDone.Set();

                //}

            }
            catch (Exception e)
            {
                Log.Error(this.GetType().ToString(),"\nException raised!");
                Log.Error("\nMessage:{0}", e.Message);
                Log.Error("\nStatus:{0}", e.Message.ToString());

            }

        }
    }
}